package cn.com.woxitech.dev.controller.api;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

import cn.com.woxitech.dev.common.APIResultFactory;
import cn.com.woxitech.dev.common.Const;
import cn.com.woxitech.dev.common.HttpClientUtils;
import cn.com.woxitech.dev.common.JSONUtils;
import cn.com.woxitech.dev.common.QiniuPhotoUploadUtils;
import cn.com.woxitech.dev.model.Lecture;
import cn.com.woxitech.dev.model.QiniuUploadResult;
import cn.com.woxitech.dev.model.RoomManager;
import cn.com.woxitech.dev.model.WmChathistoryFetch;
import cn.com.woxitech.dev.model.gen.WmApp;
import cn.com.woxitech.dev.model.gen.WmCatalog;
import cn.com.woxitech.dev.model.gen.WmLecture;
import cn.com.woxitech.dev.model.gen.WmLecturePage;
import cn.com.woxitech.dev.model.gen.WmRoom;
import cn.com.woxitech.dev.model.gen.WmUser;
import cn.com.woxitech.dev.service.AppService;
import cn.com.woxitech.dev.service.CatalogService;
import cn.com.woxitech.dev.service.LecturePageService;
import cn.com.woxitech.dev.service.LectureService;
import cn.com.woxitech.dev.service.OrganizationService;
import cn.com.woxitech.dev.service.QiniuService;
import cn.com.woxitech.dev.service.RoomService;
import cn.com.woxitech.dev.service.SMSCodeService;
import cn.com.woxitech.dev.service.UserService;

@RestController
@RequestMapping("/luyan")
public class RoomLUYANController {
	
	@Autowired
	QiniuService qiniuService;
	@Autowired
	RoomService roomService;
	@Autowired
	LectureService lectureService;
	@Autowired
	LecturePageService lecturePageService;
	@Autowired
	UserService userService;
	@Autowired
	SMSCodeService smsCodeService;
	@Autowired
	OrganizationService organizationService;
	@Autowired
	CatalogService catalogService;	
	@Autowired
	AppService appService;
	@Autowired
	private Environment env;

	@RequestMapping(value="/setting/{key}",method=RequestMethod.POST)    
	public Object setting_key(@PathVariable String key,@RequestBody String body) {
	 
			String value = this.appService.getSettingByKey(key);
	 
			return APIResultFactory.success(value);
	 
	}
	
	@RequestMapping(value="/room/{roomid}/enroll ",method=RequestMethod.POST)
	public Object room_enroll(@PathVariable String roomid, @RequestBody String body) {
		JsonNode jsonNode;
		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			jsonNode = JSONUtils.toJson(body);

			String userid =jsonNode.get("userid").asText();
			String enrollname =jsonNode.get("enrollname").asText();
			String enrolltel =jsonNode.get("enrolltel").asText();
			String enrollsn =jsonNode.get("enrollsn").asText();
			String enrollmajor =jsonNode.get("enrollmajor").asText();
			
			WmRoom room = this.roomService.getRoomsByUuid(roomid);
			
			mp.put("next", true);
			
			return APIResultFactory.success(mp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	
	
	
	@RequestMapping(value="/room/{roomuuid}/pwdsave",method=RequestMethod.POST)
	public Object room_pwd(@PathVariable String roomuuid, @RequestBody String body) {
		JsonNode jsonNode;
		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			jsonNode = JSONUtils.toJson(body);
			String pwd =jsonNode.get("pwd").asText();
			WmRoom room = this.roomService.getRoomsByUuid(roomuuid);
			room.setPwd(pwd);
			this.roomService.updateByPrimaryKey(room);
			return APIResultFactory.success(mp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	
	@RequestMapping(value="/room/{roomuuid}/catalog",method=RequestMethod.POST)
	public Object room_catalog(@PathVariable String roomuuid, @RequestBody String body) {
		JsonNode jsonNode;
		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			List<String> list = this.catalogService.getCatalogUuidStrListByRoomUuid(roomuuid);
			mp.put("catalogs", list);
			return APIResultFactory.success(mp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	
	
	@RequestMapping(value="/my_rooms",method=RequestMethod.POST)
	public Object my_rooms(@RequestBody String body) {
		JsonNode jsonNode;
		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			
			jsonNode = JSONUtils.toJson(body);

			String userid =jsonNode.get("userid").asText();
			
			String refreshtype = "all";
			if( jsonNode.get("refreshtype") != null){
				//all, head, footer
				refreshtype = jsonNode.get("refreshtype").asText();
			}
			
			String orderby = "new";
			if(jsonNode.get("orderby") != null){
				orderby = jsonNode.get("orderby").asText();
			}
			if(orderby.equals("new")){
				orderby = "createtime";
			}else if(orderby.equals("hot")){
				orderby = "attendeeCount";
			}else if(orderby.equals("live")){
				orderby = "time";
			}else{
				orderby = "createtime";
			}
			
			long timestamp = System.currentTimeMillis();
			if(jsonNode.get("timestamp") != null){
				timestamp = Long.parseLong(jsonNode.get("timestamp").asText());
			}
			
			int pos = 0;
			if(jsonNode.get("pos") != null){
				pos = Integer.parseInt(jsonNode.get("pos").asText());
			}
			
			int size = 4;
			if(jsonNode.get("size") != null){
				size = Integer.parseInt(jsonNode.get("size").asText());
			}
			int newpos = pos;
			
			WmUser user = this.userService.getUserByUuid(userid);
			if(user == null){
				user = this.userService.getUserByUnionId(userid);
			}
			List<String> roomUuidStrs = roomService.getRoomsUuidsByUserUuid(user.getUuid());

			List<WmRoom> rooms = new ArrayList<WmRoom>();
			
			if(roomUuidStrs.size() != 0){
				
				if(refreshtype.equals("all")){
					
					rooms = roomService.getRoomsByUuidList(roomUuidStrs, orderby);
					
				}else if(refreshtype.equals("head")){
					
					newpos = pos = 0;
					rooms = roomService.getHeadRefreshRoomsByUuidList(roomUuidStrs, orderby, pos, size, timestamp, true);
					
				}else if(refreshtype.equals("footer")){
					
					rooms = roomService.getFooterRefreshRoomsByUuidList(roomUuidStrs, orderby, pos, size, timestamp, true);
				}
				
			}
			newpos = newpos + rooms.size();
			
			mp.put("pos", newpos);
			mp.put("rooms", rooms);
			
			return APIResultFactory.success(mp);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	

	@RequestMapping(value = "/room/{roomuuid}/lecture",method=RequestMethod.POST)
	public Object room_lecture(@RequestBody String body, @PathVariable String roomuuid){
		Map<String, Object> mp = new HashMap<String, Object>();
		
		try {
			JsonNode jsonNode = JSONUtils.toJson(body);
			WmLecture lecture = this.lectureService.getLectureByRoomUuid(roomuuid);
			List<WmLecturePage> list = this.lecturePageService.getLecturePageByLectureUuid(lecture.getUuid());
			
			mp.put("lecture", lecture);
			mp.put("pages", list);
			return APIResultFactory.success(mp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
		
		
	}	

	@RequestMapping(value = "/room/create",method=RequestMethod.POST)
	public Object room_create(@RequestBody String body){
		Map<String, Object> mp = new HashMap<String, Object>();
		
		try {
			
			JsonNode jsonNode = JSONUtils.toJson(body);
//			{
//			"coverurl":"/attachment/default/c851864d-f7ec-401a-bcea-96021f136cbe.jpg",
//			"userid":"b69a5be1-2b74-4118-a3bf-72ab8b98799a",
//			"name":"啊啊啊啊啊",
//			"starttime":1486793460000,
//			"live_type":"2",
//			"des":"",
//			"room_type":"0"
//			}
			String systemType = jsonNode.get("systemType").asText();
			
			
			String roomuuid = UUID.randomUUID().toString();

			
			String userid = jsonNode.get("userid").asText();
			String roomname = jsonNode.get("name").asText();
			
			Date starttime = new Date(jsonNode.get("starttime").asLong());
			
			Date now = new Date(System.currentTimeMillis());
			String live_type = jsonNode.get("live_type").asText();
			String room_type = jsonNode.get("room_type").asText();
			String coverurl = jsonNode.get("coverurl").asText();
			
			String des = jsonNode.get("des").asText();
			
			WmUser user = this.userService.getUserByUuid(userid);
			
			WmRoom room = new WmRoom();
			room.setThumburl(user.getWxHeadimgurl());
			room.setCoverurl(coverurl);
			room.setLivecoverurl(coverurl);
			room.setName(roomname);
			room.setCreatetime(now);
			room.setTime(starttime);
			room.setCreatoruuid(userid);
			room.setLiveType(live_type);
			room.setRoomType(room_type);
			room.setDes(des);
			room.setUuid(roomuuid);
			room.setCreatoruuid(userid);
			room.setEndtime(new Date(System.currentTimeMillis() + 1000* 60*90));
			
			this.roomService.insertRoom(room);
			
			if(!room_type.equals("0")){

				WmApp app = this.appService.getDefaultWmApp();
				
				String publiccataloguuid = app.getDefaultcataloguuid();
				
				String room_catalog = (jsonNode.has("room_catalog")?jsonNode.get("room_catalog").asText():publiccataloguuid);
				if(!room_catalog.equals(publiccataloguuid)){
					this.catalogService.insertCatalog_Room(room_catalog, room.getUuid());
				}
				this.catalogService.insertCatalog_Room(publiccataloguuid, room.getUuid());
			}
			
			WmLecture lecture = new WmLecture();
			lecture.setCreatorid(userid);
			lecture.setRoomid(room.getUuid());
			lecture.setName(room.getName());
			lecture.setUuid(UUID.randomUUID().toString());
			this.lectureService.insertLecture(lecture);
			
			if(live_type.equals("1")){//视频直播
				
//				String key = roomuuid;
//				String rtmpstreamserver = env.getProperty("rtmpstreamserver").replace("{0}", key) ;
//				String hlsstreamserver = env.getProperty("hlsstreamserver").replace("{0}", key)  ;
//				String recordstreamserver = env.getProperty("recordstreamserver").replace("{0}", key)  ;
				
				Map<String, Object> stream_map = qiniuService.createQiniuStream();
				String rtmpstreamserver = (String)stream_map.get("publishurl");
				String key = (String)stream_map.get("streamid");
				String hlsstreamserver = (String)stream_map.get("playurl");
//				String rtmpstreamserver = "rtmp://pili-publish.haojs.com.cn/haojslive/58d0135aa95be754b002d0e7?key=2f61e450b725e60c";
//				String key = "z1.haojslive.58d0135aa95be754b002d0e7";
//				String hlsstreamserver = "http://pili-live-hls.haojs.com.cn/haojslive/58d0135aa95be754b002d0e7.m3u8";
				
				
				WmLecturePage page = new WmLecturePage();
				page.setCreatorid(userid);
				page.setLectureid(lecture.getUuid());
				page.setNum(1);
				page.setPageurl(hlsstreamserver);
				page.setPublishid(key);
				page.setThumburl(coverurl);
				page.setPublishurl(rtmpstreamserver);
				page.setTime(now);
				page.setType("live");
				this.lecturePageService.insertLecturePage(page);
			}
			
			mp.put("room",room);
			return APIResultFactory.created(mp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
		
		
	}	
	
	@RequestMapping(value = "/room/{roomuuid}/update",method=RequestMethod.POST)
	public Object room_update(@RequestBody String body, @PathVariable String roomuuid){
		Map<String, Object> mp = new HashMap<String, Object>();
		
		try {
			
			JsonNode jsonNode = JSONUtils.toJson(body);
//			{
//			"coverurl":"/attachment/default/c851864d-f7ec-401a-bcea-96021f136cbe.jpg",
//			"userid":"b69a5be1-2b74-4118-a3bf-72ab8b98799a",
//			"name":"啊啊啊啊啊",
//			"starttime":1486793460000,
//			"live_type":"2",
//			"des":"",
//			"room_type":"0"
//			}
			String systemType = jsonNode.get("systemType").asText();
			
			String userid = jsonNode.get("userid").asText();
			String roomname = jsonNode.get("name").asText();
			
			Date starttime = new Date(jsonNode.get("starttime").asLong());
			
			Date now = new Date(System.currentTimeMillis());
			String live_type = jsonNode.get("live_type").asText();
			String room_type = jsonNode.get("room_type").asText();
			String coverurl = jsonNode.get("coverurl").asText();
			
			String des = jsonNode.get("des").asText();
			
			WmUser user = this.userService.getUserByUuid(userid);
			
			WmRoom room = this.roomService.getRoomsByUuid(roomuuid);
			room.setThumburl(user.getWxHeadimgurl());
			if(!coverurl.equals("") && !coverurl.equals("null")){
				room.setCoverurl(coverurl);
				room.setLivecoverurl(coverurl);
			}
			room.setName(roomname);
			room.setCreatetime(now);
			room.setTime(starttime);
			room.setCreatoruuid(userid);
			room.setLiveType(live_type);
			room.setRoomType(room_type);
			room.setDes(des);
			room.setUuid(roomuuid);
			room.setCreatoruuid(userid);
			room.setEndtime(new Date(System.currentTimeMillis() + 1000* 60*90));
			
			this.roomService.updateByPrimaryKey(room);
			
			this.catalogService.deleteByRoomUuid(roomuuid);
			WmApp app = this.appService.getDefaultWmApp();
			String publiccataloguuid = app.getDefaultcataloguuid();
			String room_catalog = (jsonNode.has("room_catalog")?jsonNode.get("room_catalog").asText():publiccataloguuid);
			if(!room_catalog.equals(publiccataloguuid)){
				this.catalogService.insertCatalog_Room(room_catalog, room.getUuid());
			}
			this.catalogService.insertCatalog_Room(publiccataloguuid, room.getUuid());
			
			mp.put("room",room);
			return APIResultFactory.created(mp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
		
		
	}	
	
	@RequestMapping(value="/room_details",method=RequestMethod.POST)
	public Object room_details(@RequestBody String body) {
		JsonNode jsonNode;
		Map<String,Object> mp = new HashMap<String,Object>();
		
		try {
			jsonNode = JSONUtils.toJson(body);
			String roomuuid = jsonNode.get("roomid").asText();
			String userid = jsonNode.get("userid").asText();
			WmRoom room = roomService.getRoomsByUuid(roomuuid);
			if (room == null) {
				return APIResultFactory.fail();
			}

			int appid = 3;
			if(jsonNode.get("appid") != null){
				try{
					appid = jsonNode.get("appid").asInt();
				}catch(Exception e){
					appid = 3;
				}
			}
			WmApp wmApp = appService.getWmAppById(appid);
			String orgUuid = wmApp.getDefaultorguuid();
			String default_catalogUuid = wmApp.getDefaultcataloguuid();
			
			
			WmUser create_user = this.userService.getUserByUuid(room.getCreatoruuid());
			
			WmLecture lecture = lectureService.getLectureByRoomUuid(roomuuid);
			String ratio = lecture.getRatio();
			List<WmLecturePage> lecturePages = lecturePageService.getLecturePageByLectureUuid(lecture.getUuid());
			
			List<String> cataloguuids = new ArrayList<String>();
			List<String> cataloguuidStrList = catalogService.getCatalogUuidStrListByRoomUuid(roomuuid);
			for(String uuid : cataloguuidStrList){
				
				if(!uuid.equals(default_catalogUuid)){
					cataloguuids.add(uuid);
				}
			}
			
			mp.put("cover", room.getLivecoverurl());
			mp.put("wxcover", room.getCoverurl());
			mp.put("status", room.getType());
			mp.put("name", room.getName());
			mp.put("attendcount", room.getAttendeecount().intValue());
			mp.put("maxconcurrent", room.getMaxconcurrent().intValue());
			mp.put("likecount", room.getLikecount().intValue());
			mp.put("uuid", room.getUuid());
			mp.put("livetype", room.getLiveType());
			mp.put("des", room.getDes());
			mp.put("starttime", room.getTime().getTime());
			if(room.getCreatetime() == null){
				mp.put("createtime", room.getTime().getTime());
			}else{
				mp.put("createtime", room.getCreatetime().getTime());
			}
			
			String pwd = room.getPwd();
			boolean pwd_enable = true;
			if(pwd == null || pwd.equals("")){
				pwd_enable = false;
			}
			mp.put("pwd", pwd_enable);
			
			mp.put("username", create_user.getName());
			mp.put("userunionid", create_user.getWxUnionid());
			mp.put("useruuid", create_user.getUuid());
			mp.put("userheadimgurl", create_user.getWxHeadimgurl());
			
			mp.put("pages", lecturePages);
			
			mp.put("roomtype", room.getRoomType());
			mp.put("chairs", room.getRoomchairs());
			
			mp.put("cataloguuids", cataloguuids);
			
			mp.put("chairlist", this.roomService.getRoomChairs(roomuuid));
			
			mp.put("door", room.getDoortemplate());
			mp.put("tab1name", room.getTab2Name());
			mp.put("tab1html", room.getTab2Htmlsegment());
			
			if(userid == null || userid.equals("") || userid.equals("null")){
				
			}else{
				WmUser user = this.userService.getUserByUnionId(userid);
				if(user == null){
					user = this.userService.getUserByUuid(userid);
				}
				if(user == null){
					mp.put("doesfollow", 0);
					mp.put("doeslike", 0);
				}else{
					mp.put("doesfollow", this.userService.doesUserFollowUser(user.getUuid(), create_user.getUuid()));
					mp.put("doeslike", this.roomService.doesUserLikeroom(user.getUuid(), roomuuid));					
				}
			}
			
			return APIResultFactory.success(mp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	
	

	@RequestMapping(value="/room/{roomuuid}/authorize",method=RequestMethod.POST)
	public Object room_authorize(@RequestBody String body, @PathVariable String roomuuid) {
		JsonNode jsonNode;
		Map<String,Object> mp = new HashMap<String,Object>();
		
		try {
			jsonNode = JSONUtils.toJson(body);
			String pwd = jsonNode.get("pwd").asText();
			String useruuid = jsonNode.get("useruuid").asText();
			WmRoom room = roomService.getRoomsByUuid(roomuuid);
			if (room == null) {
				return APIResultFactory.fail();
			}
			if(pwd.equals(room.getPwd())){
				return APIResultFactory.success(true);
			}else{
				return APIResultFactory.success(false);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return APIResultFactory.fail();
		}
		
	}
	
	
}
